/**
 * pubsub-js
 *    订阅发布模式
 *
 * 安装： npm install pubsub-js
 * API:
 *    1. 订阅 PubSub.subscribe('订阅的消息名字', 回调函数)
 *    2. 发布 PubSub.publish('订阅的消息名字', 参数)
 *    3. 解除订阅 PubSub.unsubscribe(订阅的返回值);
 */

import React from "react";
import ReactDOM from "react-dom/client";
import PubSub from "pubsub-js";

// PubSub.subscribe("aaa", (msg, name) => {
//   console.log("aaa 的回调 111", msg, name);
// });

// PubSub.subscribe("aaa", (msg, name) => {
//   console.log("aaa 的回调 222", msg, name);
// });

// setTimeout(() => {
//   PubSub.publish("aaa", "张三");
// }, 2000);

class Hello extends React.Component {
  state = {
    name: "张三",
  };
  // 订阅消息的代码写哪儿？componentDidMount
  componentDidMount() {
    this.xxx = PubSub.subscribe("aaa", (msg, payload) => {
      console.log("Hello 收到 aaa 消息", payload);

      this.setState({
        name: payload,
      });
    });
  }

  componentWillUnmount() {
    // 取消订阅
    PubSub.unsubscribe(this.xxx);
  }

  render() {
    return (
      <div>
        <h1>Hello - {this.state.name}</h1>
      </div>
    );
  }
}

class World extends React.Component {
  fn1 = () => {
    // 发布消息
    PubSub.publish("aaa", "李四");
  };
  render() {
    return (
      <div>
        <h1>World</h1>
        <button onClick={this.fn1}>点我给Hello发消息</button>
      </div>
    );
  }
}

class App extends React.Component {
  state = {
    isShowHello: true,
  };

  render() {
    return (
      <div>
        <h1>App</h1>
        <button onClick={() => this.setState({ isShowHello: false })}>
          卸载 Hello 组件
        </button>
        {this.state.isShowHello && <Hello />}
        <World />
      </div>
    );
  }
}

const root = ReactDOM.createRoot(document.querySelector("#root"));
root.render(<App />);
